import re

from django_redis import get_redis_connection
from rest_framework import serializers
from rest_framework.response import Response
from rest_framework.settings import api_settings
from rest_framework.validators import UniqueTogetherValidator
from apps.article.models import Article
from apps.enterprise.models import Enterprise
from apps.questions.models import Label, Question, Reply
from apps.users.models import User

# class RegisterSerializer(serializers.ModelSerializer):
#     username = serializers.CharField(label='用户名')
#     token = serializers.CharField(label='JWT Token', read_only=True)
#     class Meta:
#         model = User
#         fields = ['id','username','mobile','token','avatar','password']
#         extra_kwargs = {
#             "password":{
#                 'write_only':True
#             }
#         }
#
#     def create(self, validated_data):
#         user = User.objects.create_user(**validated_data)
#         return user
#
#     def get_token(user_obj):
#         # 组织payload数据的方法
#         jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
#         # 生成jwt token数据的方法
#         jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
#
#         # 组织payload数据
#         payload = jwt_payload_handler(user_obj)
#         # 生成jwt token
#         token = jwt_encode_handler(payload)
#
#         return token
from apps.users.utils import get_token


class RegisterSerializer(serializers.ModelSerializer):
    """管理员序列化器类"""
    # username = serializers.CharField(label='用户名')
    token = serializers.CharField(label='JWT Token', read_only=True)
    sms_code = serializers.CharField(write_only=True, label='客户端返回短信验证码')

    class Meta:
        model = User
        fields = ('id', 'username', 'password', 'token', 'avatar', 'mobile', 'sms_code')

        extra_kwargs = {
            'id': {
                'read_only': True
            },
            'username': {
                'min_length': 5,
                'max_length': 20,
                'error_messages': {
                    'min_length': '用户名仅允许5-20个字符',
                    'max_length': '用户名仅允许5-20个字符',
                }
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '密码仅允许8-20个字符',
                    'max_length': '密码仅允许8-20个字符',
                }
            },
        }

    def validate_username(self, value):
        print(len(value))
        if re.match(r'\d+$', value):
            raise serializers.ValidationError('用户名须由字母、汉字、数字、下划线组成， 且不可为纯数字')

        return value

    def validate_password(self, value):
        if not re.match(r'^[a-zA-Z0-9]{8,20}$', value):
            raise serializers.ValidationError('password须由字母、数字组成')

        return value

    def validate(self, attrs):
        print(attrs)
        sms_code = attrs.get('sms_code')
        mobile = attrs.get('mobile')

        redis_conn = get_redis_connection('verify')
        sms_code_server = redis_conn.get("sms_%s" % mobile)

        if sms_code != sms_code_server.decode():
            raise serializers.ValidationError('短信验证码有误')

        return attrs

    def create(self, validated_data):
        del validated_data['sms_code']
        validated_data['nickname'] = validated_data['username']
        user = User.objects.create_user(**validated_data)
        user.token = get_token(user)
        # user.token = self.get_token(validated_data)
        return user


class QuestSerializer(serializers.ModelSerializer):
    labels = serializers.StringRelatedField(many=True)
    user = serializers.StringRelatedField()

    class Meta:
        model = Question
        fields = '__all__'


class ArticleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Article
        fields = '__all__'


class EnterpriseSerializer(serializers.ModelSerializer):
    recruits = serializers.PrimaryKeyRelatedField(read_only=True, many=True)

    class Meta:
        model = Enterprise
        fields = '__all__'


class LabelSerializer(serializers.ModelSerializer):
    # labels = serializers.StringRelatedField(read_only=True)
    class Meta:
        model = Label
        fields = ['id', 'label_name']


class ReplySerializer(serializers.ModelSerializer):
    # answer_question = serializers.
    class Meta:
        model = Reply
        fields = '__all__'


class PersonSerializer(serializers.ModelSerializer):
    labels = LabelSerializer(many=True)
    questions = QuestSerializer(many=True)
    answer_question = serializers.SerializerMethodField()
    # answer_question = serializers.StringRelatedField(read_only=True,many=True,source='replies')
    enterpises = EnterpriseSerializer(many=True)
    collected_articles = serializers.SerializerMethodField()  # 多对多关系
    username = serializers.CharField(read_only=True)

    # password = serializers.CharField(read_only=True)
    class Meta:
        model = User
        fields = ['id', 'username', 'mobile', 'realname', 'birthday', 'sex', 'avatar', 'website', 'email',
                  'city', 'address', 'labels', 'questions', 'answer_question', 'collected_articles', 'enterpises']

        # fields = '__all__'
        extra_kwargs = {
            'username': {
                'max_length': 20,
                'min_length': 5
            },
            'password': {
                'max_length': 20,
                'min_length': 8,
                'write_only': True

            },
        }

    # 重写create方法
    def create(self, validated_data):
        # 保存用户数据并对密码加密
        user = User.objects.create_user(**validated_data)
        return user

    def get_answer_question(self, obj):
        reply = Reply.objects.filter(user=obj)
        return ReplySerializer(reply, many=True).data

    def get_collected_articles(self, obj):
        # articles = Article.objects.filter(user=obj)
        articles = obj.collected_articles.all()
        return ArticleSerializer(articles, many=True).data


class UserLikeSerializer(serializers.ModelSerializer):
    """
       用户收藏
       """

    fans = serializers.PrimaryKeyRelatedField(required=True, many=True, queryset=User.objects.all())

    class Meta:
        model = User
        fields = ['fans', 'id']


class UploadSerializer(serializers.ModelSerializer):
    imgurl = serializers.CharField(read_only=True)

    class Meta:
        model = User
        fields = ['avatar', 'imgurl']

        extra_kwargs = {
            'avatar': {
                'max_length': 500,

            }}


class Article2Serializer(serializers.ModelSerializer):
    class Meta:
        model = Article
        fields = ['id', 'title']


class ArticlePersonSerializer(serializers.ModelSerializer):
    articles = Article2Serializer(many=True, read_only=True)

    class Meta:
        model = User
        fields = ['id', 'username', 'avatar', 'fans', 'articles']


class LoginSerializer(serializers.ModelSerializer):

    token = serializers.CharField(read_only=True)
    username = serializers.CharField()
    class Meta:
        model = User
        fields = ('username', 'password', 'id', 'mobile', 'avatar', "token")
        extra_kwargs = {
            'password': {
                "write_only": True
            },
            'mobile': {
                'read_only': True
            },
            'avatar': {
                'read_only': True
            },
        }

    def validate(self, attrs):
        username = attrs.get('username')
        password = attrs.get('password')
        try:
            from django.db.models import Q
            user = User.objects.get(Q(username=username) | Q(mobile=username))
        except:
            raise serializers.ValidationError("用户名或密码错误")

        if not user.check_password(password):
            raise serializers.ValidationError("用户名或密码错误")

        attrs['user'] = user

        return attrs

    def create(self, validated_data):

        user = validated_data.get('user')
        token = get_token(user)
        user.token = token

        return user